package com.chennan.book.api.rest.servicecontroller;

import com.chennan.book.api.rest.servicecontroller.dto.ExecutePlan;
import com.chennan.javabase.domain.juc.forkjoin.ForkJoinDemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

/**
 * @author chennan
 * @create 2022-01
 */
@RestController
@RequestMapping("/fork-join")
public class ForkJoinController {



    private ForkJoinPool forkJoinPool = new ForkJoinPool(8);

    @GetMapping("/start")
    public String getSubmit() throws ExecutionException, InterruptedException {
        if(forkJoinPool.getActiveThreadCount()<2){
            ForkJoinDemo.atomicLong.set(0);
            ForkJoinTask<Long> task = new ForkJoinDemo(1L,ForkJoinDemo.SUM_MAX);
            forkJoinPool.execute(task);
            return "启动分叉执行任务";
        }else{
            return "任务在执行中，不要重复启动！";
        }
    }

    @GetMapping("/checkExecute")
    public ExecutePlan checkExecute() throws ExecutionException, InterruptedException {
        ExecutePlan executePlan = new ExecutePlan();
        executePlan.setSumThreadCount(Thread.activeCount());
        executePlan.setCurrntCount(ForkJoinDemo.atomicLong.get());
        executePlan.setSumCount(ForkJoinDemo.SUM_MAX);
        executePlan.setRunThreadCount(forkJoinPool.getActiveThreadCount());
        return executePlan;

//        return "已经执行百分比:"+String.valueOf((ForkJoinDemo.atomicLong.get()/10001.00)*100)+"%"+
//                "/n,正在执行任务线程数："+forkJoinPool.getRunningThreadCount()+
//                "/n,getActiveThreadCount："+forkJoinPool.getActiveThreadCount()
//                ;
    }

}
